<template>
    <a-select
        :disabled="disabled"
        v-model:value="selected"
        :mode="mode"
        placeholder="请选择"
        style="width: 100%"
        :filter-option="filterOption"
        :show-search="true"
        :options="list"
        :fieldNames="{ label: name_key, value: table_key,}"
        @change="change"
    >
    </a-select>
</template>

<script>

export default {
    name: 'RemoteSelect',
    components: {},
    props: {
        value: {
            type: [Number, String],
            default: null,
        },
        table: {
            type: String,
            required: true,
        },
        mode: {
            type: String,
            default: 'combobox',
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        name_key: {
            type: String,
            required: true,
        }
    },
    computed: {
        table_key() {
            return `${this.table}_id`
        },
    },
    data: function () {
        return {
            selected: null,
            list: [],
        };
    },
    watch: {
      value: {
        handler(newV, oldV) {
          this.selected = newV
        },
        immediate: true
      },
    },
    created() {
        this.fetchList()
    },
    methods: {
        change(inputValue, option) {
            // console.log(111, inputValue, option)
            this.$emit('update:value', inputValue)
        },
        filterOption(inputValue, option) {
            // console.log(111, inputValue, option)
            return option[this.name_key].toLowerCase().indexOf(inputValue.toLowerCase()) !== -1
        },
        fetchList() {
            this.get('/admin/crud/list', {
                table: this.table,
            }).then(({code, paginate}) => {
                if (code === 1) {
                    this.list = paginate.data
                }
            })
        },
    }
}
</script>

<style scoped lang="less">
</style>